package com.bankcomm.api.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bankcomm.api.BankcommGet2Api;
import com.bankcomm.bean.BranchPoint;
import com.bankcomm.bean.MerchantInfo;
import com.bankcomm.bean.MerchantObj;
import com.bankcomm.bean.NodeInfo;
import com.bankcomm.bean.NodeListInfo;
import com.bankcomm.bean.NodeSearch;
import com.bankcomm.bean.OnlineBooking;
import com.bankcomm.bean.WheelObj;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.rytong.tools.utils.Utils;

/**
 * 核心接口实现类
 * 
 * @author zhang.h
 * 
 * @date 2012-5-12 下午02:38:15
 */
public class BankcommGet2ApiImpl implements BankcommGet2Api {

//	@Override
//	public ArrayList<NewInfoSketch> getInfoSketchs(String replyRes) {
//		ArrayList<NewInfoSketch> infoContents = new ArrayList<NewInfoSketch>();
//		try {
//			JSONObject replyJO = new JSONObject(replyRes);
//			
//			// 待请求页
//			String currPage = replyJO.getString("currPage");
//			LPMid.getInstance().pm_.autoTextDB_.save("newInfoCurrPage", currPage);
//			
//			// 请求参数
//			String reqParam = replyJO.getString("reqParam");
//			LPMid.getInstance().pm_.autoTextDB_.save("newInfoReqParam", reqParam);
//			
//			JSONArray infoContentJA = (JSONArray) replyJO.get("infoGroup");
//			for (int i = 0; i < infoContentJA.length(); i++) {
//				NewInfoSketch infoContent = new NewInfoSketch();
//				JSONObject infoJO = (JSONObject) infoContentJA.get(i);
//				infoContent.setTitle(infoJO.getString("title"));
//				infoContent.setDate(infoJO.getString("date"));
//				infoContent.setUrl(infoJO.getString("url"));
//				infoContents.add(infoContent);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return infoContents;
//	}
//
//	@Override
//	public String getInfoDetail(String url) {
//		String reply = null;
//		try {
//			reply = (String) LPMid.getInstance().hm_.sendPostRequest(url, null, null, null, null);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return reply;
//	}

	@Override
	public LinkedHashMap<Integer, BranchPoint> getBranchsJson(String url) throws Exception {
		List<String> urls = LPMid.getInstance().urlList;

		// 先清除再添加, 否则url个数会一直累加
		if (urls != null && urls.size() > 0) {
			urls.clear();
		}

		/** 网点集合 */
		LinkedHashMap<Integer, BranchPoint> branchHM = new LinkedHashMap<Integer, BranchPoint>();

		/** 经度StringBuffer */
		StringBuffer lonSB = new StringBuffer();

		/** 纬度StringBuffer */
		StringBuffer latSB = new StringBuffer();

		String reply = (String) LPMid.getInstance().hm_.sendPostRequest(url, null, null, null, null);
		Utils.printOutToConsole("周边搜索报文:"+reply);
		if (reply != null && reply.length() > 0) {
			JSONArray pointJA = new JSONArray(reply);
			int branchCount = pointJA.length();
			for (int i = 0; i < branchCount; i++) {
				BranchPoint branchPoint = new BranchPoint();
				JSONObject branchJO = (JSONObject) pointJA.get(i);
				branchPoint.setName(branchJO.getString("name"));
				branchPoint.setAddress(branchJO.getString("address"));
				branchPoint.setPhone(branchJO.getString("phone"));
				branchPoint.setBranchBody(branchJO.getString("branchBody"));

				// 经度
				branchPoint.setLonPoint(branchJO.getString("lonPoint"));
				lonSB.append(branchJO.getString("lonPoint"));
				lonSB.append(",");

				// 纬度
				branchPoint.setLatPoint(branchJO.getString("latPoint"));
				latSB.append(branchJO.getString("latPoint"));
				latSB.append(",");

				// 加入集合
				branchHM.put(i, branchPoint);

				if ((i + 1) % 20 == 0 || (i + 1) == branchCount) {
					lonSB = lonSB.deleteCharAt(lonSB.length() - 1);
					latSB = latSB.deleteCharAt(latSB.length() - 1);

					String excursionUrl = ConfigManager.MAP_BAIDU_URL + "from=2&to=4&x=" + lonSB.toString() + "&y=" + latSB.toString()
							+ "&mode=1";
					urls.add(excursionUrl);

					// 清空
					lonSB.setLength(0);
					latSB.setLength(0);
				}
			}
		}
		return branchHM;
	}

	@Override
	public MerchantObj getMerchantInfos(String url) throws Exception {
		MerchantObj merchantObj = new MerchantObj();
		String reply = (String) LPMid.getInstance().hm_.sendPostRequest(url, null, null, null, null);
		JSONObject merchantObjJO = new JSONObject(reply);
		// 当前页, 保存以便加载更多使用.
		String currPage = merchantObjJO.getString("currPage");
		merchantObj.setCurrPage(currPage);
		LPMid.getInstance().pm_.autoTextDB_.save("merchantCurrPage", currPage);

		// 地区
		if (merchantObjJO.has("merchantRegion")) {
			JSONArray merchantRegionJA = merchantObjJO.getJSONArray("merchantRegion");
			WheelObj merchantRegionWheelObj = initWheelObjData(merchantRegionJA);
			merchantObj.setMerchantRegion(merchantRegionWheelObj);
		}

		// 类型
		if (merchantObjJO.has("merchantTypes")) {
			JSONArray merchantTypesJA = merchantObjJO.getJSONArray("merchantTypes");
			WheelObj merchantTypesWheelObj = initWheelObjData(merchantTypesJA);
			merchantObj.setMerchantTypes(merchantTypesWheelObj);
		}

		// 列表
		JSONArray merchantListJA = merchantObjJO.getJSONArray("merchantList");
		ArrayList<MerchantInfo> merchantInfos = new ArrayList<MerchantInfo>();
		for (int i = 0; i < merchantListJA.length(); i++) {
			MerchantInfo merchantInfo = new MerchantInfo();
			JSONObject merchantListJO = (JSONObject) merchantListJA.get(i);
			merchantInfo.setMerId(merchantListJO.getString("merId"));
			merchantInfo.setMerchantImageUrl(merchantListJO.getString("merchantImageUrl"));
			merchantInfo.setMerchantName(merchantListJO.getString("merchantName"));
			merchantInfo.setMerchantIntro(merchantListJO.getString("merchantIntro"));
			merchantInfos.add(merchantInfo);
		}
		merchantObj.setMerchantList(merchantInfos);
		return merchantObj;
	}

	@Override
	public Map<String, NodeSearch> getNodeSearchData(String nodeSearchUrl) throws Exception {
		Map<String, NodeSearch> nodeSearchMap = new HashMap<String, NodeSearch>();

		String reply = (String) LPMid.getInstance().hm_.sendPostRequest(nodeSearchUrl, null, null, null, null);
		JSONObject nodeSearchJO = new JSONObject(reply);
		// 城市
		String cityJson = nodeSearchJO.getString("citys");
		JSONObject cityJO = new JSONObject(cityJson);
		String cityParamName = cityJO.getString("paramName");
		String cityData = cityJO.getString("data");
		nodeSearchMap.put("citys", new NodeSearch(cityParamName, cityData));

		// 类型
		String typeJson = nodeSearchJO.getString("types");
		JSONObject typeJO = new JSONObject(typeJson);
		String typeParamName = typeJO.getString("paramName");
		String typeData = typeJO.getString("data");
		nodeSearchMap.put("types", new NodeSearch(typeParamName, typeData));

		return nodeSearchMap;
	}

	@Override
	public NodeListInfo getNodes(String url) throws Exception {
		NodeListInfo nodeListInfo = new NodeListInfo();

		String reply = (String) LPMid.getInstance().hm_.sendPostRequest(url, null, null, null, null);
		if (reply != null && reply.length() > 0) {
			JSONObject nodeListJO = new JSONObject(reply);
			String msg = nodeListJO.getString("msg");
			String currPage = nodeListJO.getString("currPage");
			LPMid.getInstance().pm_.autoTextDB_.save("nodeSearchCurrPage", currPage);

			ArrayList<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();
			String marks = nodeListJO.getString("marks");
			JSONArray marksJA = new JSONArray(marks);
			for (int i = 0; i < marksJA.length(); i++) {
				JSONObject markJO = (JSONObject) marksJA.get(i);
				nodeInfos.add(new NodeInfo(markJO.getString("markName"), markJO.getString("markAddr"), markJO.getString("markPhone"),
						markJO.getString("markCode")));
			}

			nodeListInfo.setMsg(msg);
			nodeListInfo.setCurrPage(currPage);
			nodeListInfo.setNodeInfos(nodeInfos);
		}

		return nodeListInfo;
	}

	@Override
	public HashMap<String, OnlineBooking> getOnlineBookingData(String url, String urlBody) throws Exception {
		
		Utils.printOutToConsole(url);
		Utils.printOutToConsole(urlBody);
		HashMap<String, OnlineBooking> onlineBookingMap = new HashMap<String, OnlineBooking>();
		String reply = (String) LPMid.getInstance().hm_.sendPostRequest(url, urlBody, null, null, null);
		if (reply != null && reply.length() > 0) {
			JSONObject onlineBookingJO = new JSONObject(reply);
			if (onlineBookingJO.has("error")) {
				onlineBookingMap.put("error", new OnlineBooking("", onlineBookingJO.getString("error")));
			} else {
				String nodeName = onlineBookingJO.getString("nodeName");
				JSONObject nodeNameJO = new JSONObject(nodeName);
				onlineBookingMap.put("nodeName", new OnlineBooking(nodeNameJO.getString("paramName"), nodeNameJO.getString("data")));

				String bookingData = onlineBookingJO.getString("bookingData");
				JSONObject bookingDataJO = new JSONObject(bookingData);
				onlineBookingMap.put("bookingData",
						new OnlineBooking(bookingDataJO.getString("paramName"), bookingDataJO.getString("data")));

				String beginBookingData = onlineBookingJO.getString("beginBookingData");
				JSONObject beginBookingDataJO = new JSONObject(beginBookingData);
				onlineBookingMap.put("beginBookingData", new OnlineBooking(beginBookingDataJO.getString("paramName"), beginBookingDataJO
						.getString("data")));

				String bookingPhone = onlineBookingJO.getString("bookingPhone");
				JSONObject bookingPhoneJO = new JSONObject(bookingPhone);
				onlineBookingMap.put("bookingPhone", new OnlineBooking(bookingPhoneJO.getString("paramName"), bookingPhoneJO
						.getString("data")));
			}
		}
		return onlineBookingMap;
	}

	private WheelObj initWheelObjData(JSONArray merchantRegionJA) {
		String[] bigClass = null;
		String[][] smallClass = null;
		HashMap<Integer, String> bigMap = new HashMap<Integer, String>(); // 大类数据
		HashMap<Integer, HashMap<Integer, String>> smallMap = new HashMap<Integer, HashMap<Integer, String>>(); // 小类数据
		WheelObj wheelObj = new WheelObj();
		try {
			if (merchantRegionJA.length() > 0) {
				bigClass = new String[merchantRegionJA.length()];
				smallClass = new String[merchantRegionJA.length()][];
				for (int i = 0; i < merchantRegionJA.length(); i++) {
					JSONObject jsonObject = new JSONObject(merchantRegionJA.getString(i));
					String key = jsonObject.keys().next().toString();
					bigClass[i] = key;

					Object value = jsonObject.get(key);
					if (value instanceof JSONArray) {
						String[] valueCity = null;
						JSONArray valueJson = new JSONArray(value.toString());
						if (valueJson.length() > 0) {
							valueCity = new String[valueJson.length()];
							HashMap<Integer, String> cityMap = new HashMap<Integer, String>();
							for (int j = 0; j < valueJson.length(); j++) {
								JSONObject valJsonObject = new JSONObject(valueJson.getString(j));
								String valKey = valJsonObject.keys().next().toString();
								valueCity[j] = valKey;

								// 小类
								cityMap.put(j, valJsonObject.get(valKey).toString());
							}
							smallMap.put(i, cityMap);
							smallClass[i] = valueCity;
						}
					} else {
						// 大类
						bigMap.put(i, value.toString());
						smallClass[i] = new String[] {};
					}
				}
			}
			wheelObj.setBigClass(bigClass);
			wheelObj.setSmallClass(smallClass);
			wheelObj.setBigMap(bigMap);
			wheelObj.setSmallMap(smallMap);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return wheelObj;
	}

}
